package com.cyys.modules.system.service.recycle;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyys.common.ql.AR;
import com.cyys.common.services.CyysBaseService;
import com.cyys.common.utils.StringUtil;
import com.cyys.modules.core.sysParam.ParamBasicUtil;
import com.cyys.modules.core.sysParam.ParamConstants;
import com.cyys.modules.system.dao.recycle.SysRecycleDao;
import com.cyys.modules.system.model.recycle.SysRecycle;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description 系统回收站Service层
 * @author LC
 * @date 2020-10-30
 */
@Service("sysRecycleService")
@Transactional(readOnly = true)
public class SysRecycleService extends CyysBaseService<SysRecycleDao, SysRecycle> {

    /**
     * 获取所有开放回收站的表
     * @return
     * @
     */
    public Map<String,String> getAllTableComment(){
        Map<String, String> map = new HashMap<>();
        List<SysRecycle> list = dao.getAllTableComment();
        for (SysRecycle sysRecycle : list) {
            map.put(sysRecycle.getTableName(),sysRecycle.getTableComment());
        }
        return map;
    }

    /**
     * 回收站初始化
     * @return
     * @
     */
    @Transactional(readOnly = false)
    public AR initSysResycle() {
        List<String> alreadyList = new ArrayList<>();
        /**现有所有表加入List中不新增**/
        List<SysRecycle> currentTableList = dao.selectList(null);
        for(SysRecycle currentTable :currentTableList){
            alreadyList.add(currentTable.getTableName());
        }
        List<SysRecycle> list = dao.listTable();
        /**创建所有表和列***/
        for(SysRecycle sysRecycle : list){
            /***比较现有表和数据库中的表，如果存在不进行操作***/
            if(!alreadyList.contains(sysRecycle.getTableName())){
                dao.insert(sysRecycle);
            }
        }
        return AR.ok("初始化成功");
    }

    /**
     * 数据恢复
     * @return
     * @
     */
    @Transactional(readOnly = false)
    public AR dataRecovery(String id, String tableName) {
        dao.recovery(id,tableName);
        return AR.ok("数据恢复成功");
    }

    /**
     * 数据删除
     * @return
     * @
     */
    @Transactional(readOnly = false)
    public AR dataDeletion(String id, String tableName) {
        dao.deletion(id,tableName);
        return AR.ok("数据删除成功");
    }

    /**
     * 查询不同表的不同数据
     * @param page
     * @param tableName 表名
     * @param queryParams 查询参数
     * @return
     * @
     */
    public Page listResourceInfo(Page page, String tableName, String queryParams) {
        Map<String, String> map= new HashedMap<>();
        if(StringUtil.isNotBlank(queryParams)){
            map=  (Map) JSON.parse(queryParams);
        }
        List<HashMap<String, Object>> list = dao.listByTableName(page, tableName, map);
        return page.setRecords(list);
    }

    /**
     * 查询不同表的不同数据（此种方法取列有点问题，没数据就没有列，而且用Map返回查询数据时当值为空时该列就不显示，排序也很乱）
     * @param tableName
     * @return
     * @
     */
//    public HashMap<String,Object> getCols(String tableName) {
//        return dao.getCols(tableName);
//    }

    /**
     * 查询表的所有列数据
     * @param tableName
     * @return
     */
    public List<Map> listTableColumn(String tableName) {
        return dao.listTableColumn(tableName);
    }

    /**
     * 查询不同表的不同数据
     * @param tableName
     * @return
     * @
     */
    public SysRecycle getRecycleByTableName(String tableName) {
        SysRecycle recycle= new SysRecycle();
        recycle.setTableName(tableName);
        return dao.selectOne(new QueryWrapper<>(recycle));
    }

    /**
     * 查询不同表的不同数据
     * @param tableName 表名
     * @return
     * @
     */
    public List<Map> listForSetQueryCol(String tableName) {
        List<Map> columnList = new ArrayList<>();
        SysRecycle recycle = getRecycleByTableName(tableName);
        if (recycle != null) {
            columnList = dao.listTableColumn(recycle.getTableName());
            if (StringUtil.isNotBlank(recycle.getQueryCols())) {
                Map<String, Map> maps = (Map) JSON.parse(recycle.getQueryCols());
                columnList.stream().forEach(data -> {
                    if (maps.containsKey(data.get("columnName"))) {
                        Map map = maps.get(data.get("columnName"));
                        String inputType = map.get("inputType").toString();
                        map.put("inputTypeName", ParamBasicUtil.getParamBasicTypeMap().get(ParamConstants.QUERY_INPUT_TYPE).get(inputType));
                        if(map.get("sysParam")!=null){//系统参数查询框
                            String sysParam = map.get("sysParam").toString();
                            map.put("sysParamName", ParamBasicUtil.getParamBasic().get(sysParam));
                        }
                        data.put("queryColInfo", maps.get(data.get("columnName")));
                    }
                });
            }
        }
        return columnList;
    }

    /**
     * 设置查询列
     * @param isQueryCol 是否设置为查询列
     * @param tableName 表名
     * @param columnName 列名
     * @param columnComment 列注释，用于设置默认查询框标签
     * @return
     */
    @Transactional(readOnly = false)
    public AR setQueryCol(String isQueryCol, String tableName, String columnName, String columnComment) {
        if(StringUtil.isBlank(isQueryCol)){
            return AR.failed("缺少参数【isQueryCol】");
        }else if(StringUtil.isBlank(tableName)){
            return AR.failed("缺少参数【tableName】");
        }else if(StringUtil.isBlank(columnName)){
            return AR.failed("缺少参数【columnName】");
        }
        SysRecycle recycle= getRecycleByTableName(tableName);
        if(recycle== null){
            return AR.failed("表："+tableName+"的回收站记录不存在");
        }
        Map<String,Object> maps = new HashedMap<>();
        if(StringUtil.isNotBlank(recycle.getQueryCols())){
            maps = (Map) JSON.parse(recycle.getQueryCols());
        }
        if("1".equals(isQueryCol)){//设置为查询列
            Map<String, Object> map= new HashedMap<>();
            if(StringUtil.isNotBlank(columnComment)){
                map.put("inputLabel",columnComment);
            }
            map.put("inputType","1"); //默认值，1：文本框
            map.put("sort",0);//默认值
            maps.put(columnName, map);
        }else{//取消查询列
            maps.remove(columnName);
        }
        SysRecycle updateObj= new SysRecycle();
        updateObj.setId(recycle.getId());
        updateObj.setQueryCols(JSON.toJSONString(maps));
        dao.updateById(updateObj);
        return AR.ok("设置成功");
    }

    /**
     * 编辑查询列信息
     * @param tableName 表名
     * @param columnName 列名
     * @param queryColInfo 查询列信息
     * @return
     */
    @Transactional(readOnly = false)
    public AR editQueryColInfo(String tableName, String columnName, String queryColInfo) {
        if(StringUtil.isBlank(tableName)){
            return AR.failed("缺少参数【tableName】");
        }else if(StringUtil.isBlank(columnName)){
            return AR.failed("缺少参数【columnName】");
        }else if(StringUtil.isBlank(queryColInfo)){
            return AR.failed("缺少参数【queryColInfo】");
        }
        SysRecycle recycle= getRecycleByTableName(tableName);
        if(recycle== null){
            return AR.failed("表："+tableName+"的回收站记录不存在");
        }
        Map<String,Object> maps = new HashedMap<>();
        if(StringUtil.isNotBlank(recycle.getQueryCols())){
            maps = (Map) JSON.parse(recycle.getQueryCols());
        }
        maps.put(columnName, JSON.parse(queryColInfo));
        SysRecycle updateObj= new SysRecycle();
        updateObj.setId(recycle.getId());
        updateObj.setQueryCols(JSON.toJSONString(maps));
        dao.updateById(updateObj);
        return AR.ok("设置成功");
    }

    /**
     * 返回查询列信息
     * @param tableName 表名
     * @return
     */
    public List<Map> getQueryColList(String tableName) {
        List<Map> queryCols= new ArrayList<>();
        SysRecycle recycle= getRecycleByTableName(tableName);

        if(StringUtil.isNotBlank(recycle.getQueryCols())){
            Map<String, Map> queryColsInfo = (Map) JSON.parse(recycle.getQueryCols());
            //组装成List
            queryCols= queryColsInfo.entrySet().stream().map(m->{
                Map map= m.getValue();
                map.put("colName", m.getKey());
                if(map.containsKey("sysParam")){//存入查询列对应的字典参数列表
                    map.put("sysParamList",ParamBasicUtil.getParamBasicTypeList().get(map.get("sysParam")));
                }
                return map;
            }).collect(Collectors.toList());
            //list按sort排序
            queryCols= queryCols.stream().sorted(Comparator.comparing(d -> Integer.parseInt(d.get("sort").toString()))).collect(Collectors.toList());;
        }
        return queryCols;
    }
}
